package com.wechatapp.mengyao.poetry.biz;

import com.fasterxml.jackson.core.type.TypeReference;
import com.wechatapp.mengyao.poetry.core.JsonUtils;
import com.wechatapp.mengyao.poetry.vo.DailyPoetryView;
import com.wechatapp.mengyao.poetry.entity.ChinesePoetry;
import com.wechatapp.mengyao.poetry.entity.DailyPoetry;
import com.wechatapp.mengyao.poetry.mapper.ChinesePoetryMapper;
import com.wechatapp.mengyao.poetry.service.DailyPoetryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;

/**
 * @author yanghuaxu
 * @date 2025/6/19 13:17
 */
@Service
@Slf4j
public class DailyPoetryBiz {

    @Autowired
    private ImageGenerationBiz imageGenerationBiz;
    @Autowired
    private DailyPoetryService dailyPoetryService;
    @Autowired
    private ChinesePoetryMapper chinesePoetryMapper;

    public DailyPoetryView getTodayPoetry() {
        DailyPoetry todayPoetry = dailyPoetryService.getTodayPoetry();
        ChinesePoetry poetry = null;
        if (ObjectUtils.isEmpty(todayPoetry)) {
            poetry = dailyPoetryService.getRandomPoetry();
            ImageGenerationBiz.ImageResult imageResult = imageGenerationBiz.generateImage(poetry.getTranslation());
            if (!StringUtils.hasText(imageResult.getBase64())) {
                // 如果生成图片失败，直接忽略
                return new DailyPoetryView();
            }
            todayPoetry = new DailyPoetry();
            todayPoetry.setImageUrl(imageResult.getUrl());
            todayPoetry.setBase64Data(imageResult.getBase64());
            todayPoetry.setCreateDate(LocalDate.now());
            todayPoetry.setPoetryId(poetry.getId());
            dailyPoetryService.saveDailyPoetry(todayPoetry);
        } else {
            poetry = chinesePoetryMapper.selectByPrimaryKey(todayPoetry.getPoetryId());
        }
        DailyPoetryView result = new DailyPoetryView();
        result.setAuthor(poetry.getAuthor());
        result.setContent(JsonUtils.parseList(poetry.getContent(), new TypeReference<List<String>>() {
        }));
        result.setDynasty(poetry.getDynasty());
        result.setTitle(poetry.getTitle());
        result.setBase64(todayPoetry.getBase64Data());
        return result;
    }


}
